package com.easychat.controller;

import com.easychat.entity.enums.ResponseCodeEnum;
import com.easychat.entity.vo.ResponseVo;
import com.easychat.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;

/**
 * 全局异常处理
 * @RestControllerAdvice 注解 用于全局异常处理、全局数据绑定，可以捕获Controller中抛出的异常，并对一场进行统一处理
 * @author kyle.li
 * @version 1.0
 * @description: TODO
 * @date 2024/6/25 21:03
 */
@RestControllerAdvice
public class AGlobalExceptionHandleController extends ABaseController{
    private static final Logger logger = LoggerFactory.getLogger(AGlobalExceptionHandleController.class);

    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request){
        logger.error("请求错误，请求地址{}，错误信息：", request.getRequestURL(), e);
        ResponseVo ajaxResponse = new ResponseVo();
        //404
        if(e instanceof NoHandlerFoundException){
            ajaxResponse.setCode(ResponseCodeEnum.CODE_404.getCode());
            ajaxResponse.setMsg(ResponseCodeEnum.CODE_404.getMessage());
            ajaxResponse.setStatus(STATUS_ERROR);
        }else if(e instanceof BusinessException){
            //业务错误
            BusinessException biz = (BusinessException) e;
            ajaxResponse.setCode(String.valueOf(biz.getCode()).equals("") ? ResponseCodeEnum.CODE_600.getCode() : biz.getCode());
            ajaxResponse.setMsg(biz.getMessage());
            ajaxResponse.setStatus(STATUS_ERROR);
        } else if (e instanceof BindException || e instanceof MethodArgumentTypeMismatchException) {
            //参数类型错误
            ajaxResponse.setCode(ResponseCodeEnum.CODE_600.getCode());
            ajaxResponse.setMsg(ResponseCodeEnum.CODE_600.getMessage());
            ajaxResponse.setStatus(STATUS_ERROR);
        } else if (e instanceof DuplicateKeyException) {
            //主键冲突
            ajaxResponse.setCode(ResponseCodeEnum.CODE_601.getCode());
            ajaxResponse.setMsg(ResponseCodeEnum.CODE_601.getMessage());
            ajaxResponse.setStatus(STATUS_ERROR);
        }
        return ajaxResponse;
    }
}
